(function ($) {

    var countdown = 60;

    $("#city_1").citySelect({
        nodata: "none",
        required: false
    });
    $("#city_2").citySelect({
        prov: "南京",
        nodata: "none"
    });

    $(window).load(function () {
        stNavHover();
        isShowStickyNav();
    });

    function s4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1).toUpperCase();
    }

    function createGuid() {
        return (s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4());
    }

    function setCookie(name, value, expires, path, domain, secure) {
        var today = new Date();
        today.setTime(today.getTime());
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));
        document.cookie = name + "=" + escape(value) +
            ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ((secure) ? ";secure" : "");
    }

    function getCookie(checkName) {
        var a_all_cookies = document.cookie.split(';');
        var a_temp_cookie = '';
        var cookieName = '';
        var cookie_value = '';
        var b_cookie_found = false;
        for (i = 0; i < a_all_cookies.length; i++) {
            a_temp_cookie = a_all_cookies[i].split('=');
            cookieName = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
            if (cookieName == checkName) {
                b_cookie_found = true;
                if (a_temp_cookie.length > 1) {
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                return cookie_value;
            }
            a_temp_cookie = null;
            cookieName = '';
        }
        if (!b_cookie_found) {
            return null;
        }
    }

    function initTracker(guidCookieName, baseDomain, cookiePath) {
        if (guidCookieName) {
            var expire = 365 * 5;
            var guid = getCookie(guidCookieName);
            if (null == guid) {
                guid = createGuid();
                setCookie(guidCookieName, guid, expire, cookiePath, baseDomain);
            } else {
                setCookie(guidCookieName, guid, expire + 1, cookiePath, baseDomain);
            }
        }
    }

    initTracker('aQQ_guid', document.domain, '/');
    $("#verify_code").attr('src', '/picture/verify/code/' + new Date().getTime());

    $('#picture_code').bind('keyup', function () {

        $('#picture_code').removeClass('error');
        var picture_code = $(this).val();
        if (picture_code.length == 4) {
            $(this).attr('disabled', true);

            var name = $('#edit-name').val();

            $.ajax({
                type: "POST",
                async: true,
                url: '/send/phone/code',
                data: {
                    'picture_code': picture_code,
                    'phone': name
                },
                dataType: "json",
                success: function (data) {

                    if (data.status == 'ok') {
                        $('#picture_code_box').hide();
                        $('#picture_code').removeAttr('disabled');
                        $("#verify_code").attr('src', '/picture/verify/code/' + new Date().getTime());
                        settime();
                    } else {
                        $('#picture_code').removeAttr('disabled');
                        $('#picture_code').addClass('error');
                    }
                }
            });

        }
    });

    $('#sendPhoneCodeBtn').bind('click', function () {
        var name = $('#edit-name').val();
        var reg = /^[1][3,4,5,7,8][0-9]{9}$/;

        var picture_code = $('#picture_code').val();

        if (name == '') {
            $('#edit-name-error').hide();
            $('#edit-name').addClass('error');
            $('.name_error').html('<span id="edit-name-error" class="error">请输入手机号</span>');
            return false;

        } else if (!reg.test(name)) {
            $('#edit-name-error').hide();
            $('#edit-name').addClass('error');
            $('.name_error').html('<span id="edit-name-error" class="error">您输入的手机号不正确</span>');
            return false;
        }

        $.ajax({
            type: "POST",
            async: true,
            url: '/check/has-name',
            data: {
                'phone': name
            },
            dataType: "json",
            success: function (data) {

                if (data.status == 0) {
                    $('#edit-name-error').hide();
                    $('#edit-name').addClass('error');
                    $('.name_error').html('<span id="edit-name-error" class="error">' + data.message + '</span>');
                    return false;
                } else {
                    $('#picture_code_box').show();
                }
            }
        });

        if (picture_code == '') {
            $('#picture_code').addClass('error');
            return false;
        }

        return false;
    });

    function settime() {
        var code = $('#sendPhoneCodeBtn');
        if (countdown == 0) {
            code.attr('disabled', false);
            code.html("获取验证码");
            countdown = 60;
            return false;
        } else {
            code.attr('disabled', true);
            code.html("重新发送(" + countdown + ")");
            countdown--;
        }
        setTimeout(function () {
            settime();
        }, 1000);
    }

    $('#edit-name').bind('keyup', function () {
        $(this).removeClass('error');
        $('.name_error').html('');
    });

    $('#send2').bind('click', function () {
        $('.name_error').html('');
    });

    //登录
    var timer;
    $(".mod-signin").hover(function(){
        clearTimeout(timer);
        $(this).addClass("immediate");
        $(this).find(".headercontent").show();
    },function(){
        timer=setTimeout(function(){
            $(".mod-signin").removeClass("immediate");
            $(".mod-signin").find(".headercontent").hide();
        },2000)
    });
    $(".js-close").click(function () {
        $(this).parents(".mod-signin").removeClass("immediate");
        $(this).parents(".headercontent").hide();
    });
    //手机端导航
    $('#nav-offscreen').mmenu({
            drag: true,
            extensions: ['pagedim-black'],
            setSelected: true,
            pageScroll: {
                scroll: true,
                update: true
            },
        }, {
            offCanvas: {
                pageSelector: ".page-wrapper"
            }
        }
    );
    //默认展开当前页面菜单面板
    var api = $("#nav-offscreen").data("mmenu");
    var url = window.location.pathname;
    var parameter = window.location.search;
    //console.log(url);
    $("#nav-offscreen .mm-panels .mm-listitem a").each(function () {
        var href = $(this).attr("href");
        var panelId;
        if (href == url + parameter) {
            console.log(url + parameter);
            if ($(this).siblings().size() > 0 && $(this).siblings().hasClass("mm-btn_next")) {
                if(href=="/"){
                    api.openPanel($("#mm-1"));
                }else{
                    panelId = $(this).siblings("a").attr("href");
                    api.openPanel($(panelId));
                }
            } else {
                panelId = $(this).parents(".mm-panel").attr("id");
                if ($(this).hasClass("b-secondary")) {
                    var p1 = parseInt(panelId.substring(panelId.indexOf('-') + 1)) + 1;
                    var p2 = panelId.substring(0, panelId.lastIndexOf('-'));
                    panelId = p2 + "-" + p1.toString();
                }
                api.openPanel($("#" + panelId));
            }
        }
    });


    $(window).resize(function () {
        if ($(window).innerWidth() >= 768) {
            $("html").removeClass().addClass("responsive");
            $(".mm-menu.mm-menu_offcanvas").removeClass("mm-menu_opened");
        }
    });
    //banner
    $('#nb-carousel_1 .carousel-inner').slick({
        dots: true,
        autoplay: true,
        autoplaySpeed: 2000,
        cssEase: "linear"
    });
    //导航
    function stNavHover() {
        $(".js-mod-nav-sub .sub>li").hover(function () {
            $(this).siblings("li").find("a").removeClass("selected");
            $(this).siblings("li").find(".sub-sub").hide();
            $(this).find("a.b-secondary").addClass("selected");
            $(this).find(".sub-sub").show();
            $("footer .mod.mod-grey-box").show();
            $(this).parents(".js-mod-nav-sub").css({
                "position": "absolute",
                "height": $(this).find(".sub-sub").height() + 80
            });
        }, function () {
            $(this).find("a.b-secondary").removeClass("selected");
            $(this).find(".sub-sub").hide();
            $("footer .mod.mod-grey-box").hide();
            $(this).parents(".js-mod-nav-sub").css({"position": "relative", "height": "auto"});
        });

        $(".mod-nav-main ul.main li:not(:nth-child(3))").hover(function () {
            $(this).addClass("hover").siblings("li").removeClass("hover");
            $(".js-mod-nav-sub ul.sub").eq($(this).index()).show().siblings("ul.sub").hide();
        }, function () {
            $(this).removeClass("hover");
        });
        $(".js-mod-nav-sub").mouseleave(function () {
            $(".js-mod-nav-sub ul.sub").eq($(".mod-nav-main ul.main li.active").index()).show().siblings("ul.sub").hide();
        });
    }

    //登录验证
    $('#user-login').validate({
        rules: {
            name: {required: true},
            pass: {required: true}
        },
        messages: {
            name: {
                required: "手机号不能为空",
            },
            pass: {
                required: "密码不能为空"
            }
        }
    });
    //注册验证
    $('#user-register-form').validate({
        errorElement: "span",
        errorPlacement: function (error, element) {
            $(element).parents(".form_control").append(error);
        },
        rules: {
            name: {
                required: true,
                minlength: 11,
                maxlength: 11,
            },
            phone_code: {
                required: true,
            },
            "field_realname[und][0][value]": {
                required: true,
                minlength: 2
            },
            "field_company[und][0][value]": {
                required: true,
            },
            mail: {
                required: true,
                email: true
            },
            "pass[pass1]": {
                required: true,
                minlength: 6
            },
            "pass[pass2]": {
                required: true,
                minlength: 6,
                equalTo: "#edit-pass-pass1"
            },
            //agree: "required"
        },
        messages: {
            name: {
                required: "请输入手机号",
                minlength: "请输入正确的手机号",
                maxlength: "请输入正确的手机号"
            },
            phone_code: {
                required: "请输入验证码",
            },
            "field_realname[und][0][value]": {
                required: "请输入姓名",
                minlength: "用户名必需由两个字母组成"
            },
            "field_company[und][0][value]": {
                required: "请输入工作单位",
            },
            mail: {
                required: "请输入邮箱",
                email: "邮箱格式不正确"
            },
            "pass[pass1]": {
                required: "请输入密码",
                minlength: "密码长度不能小于 6 个字符"
            },
            "pass[pass2]": {
                required: "请输入密码",
                minlength: "密码长度不能小于 6 个字符",
                equalTo: "两次密码输入不一致"
            },
            //agree: "请接受我们的声明"
        }
    });
    //账号信息修改验证
    $('#edit-account-form').validate({
        errorElement: "span",
        errorPlacement: function (error, element) {
            $(element).parents(".form_control").append(error);
        },
        rules: {
            username: {
                required: true,
                minlength: 2
            },
            email: {
                required: true,
                email: true
            },
            password: {required: true},
        },
        messages: {
            username: {
                required: "请输入用户名",
                minlength: "用户名必需由两个字母组成"
            },
            email: {
                required: "邮箱不能为空",
                email: "邮箱格式不正确"
            },
            password: {
                required: "密码不能为空"
            }
        }
    });
    //忘记密码
    $("#forgot-pwd").colorbox({
        width: "auto",
        height: "auto",
        inline: true,
        href: '#forgot-pw-popup',
        fixed: true
    });
    //忘记密码验证
    $('#forgot-pw-validate').validate({
        rules: {
            email: {required: true, email: true},
        },
        messages: {
            email: {
                required: "邮箱不能为空",
                email: "邮箱格式不正确"
            }
        }
    });

    //修改密码
    $("#edit-pwd").colorbox({
        width: "auto",
        height: "auto",
        inline: true,
        href: '#edit-pw-popup',
        fixed: true
    });
    //修改密码验证
    $('#edit-pw-validate').validate({
        rules: {
            editPwd: {
                required: true,
                minlength: 5
            },
            editPwdConfirm: {
                required: true,
                minlength: 5,
                equalTo: "#editPwd"
            },
        },
        messages: {
            editPwd: {
                required: "请输入密码",
                minlength: "密码长度不能小于 5 个字母"
            },
            editPwdConfirm: {
                required: "请输入密码",
                minlength: "密码长度不能小于 5 个字母",
                equalTo: "两次密码输入不一致"
            },
        }
    });
    //显示置顶一级菜单
    function loadFirstNav() {
        if ($(".js-navsticky .container").children(".js-navcloned").length <= 0) {
            var nav1Html = $(".navmain .mod-nav-main").clone().addClass("cloned");
            var $nav1div = $("<div class='navcloned js-navcloned'></div>");
            $nav1div.html(nav1Html);
            $nav1div.appendTo(".navsticky .container");
        }
    }

    //显示置顶二三级菜单
    function loadStNav() {
        if ($(".js-navsticky").children(".mod-nav-sub").length <= 0) {
            var nav1Html = $(".mod-nav-sub.js-mod-nav-sub").clone().addClass("cloned");
            $(".navsticky.js-navsticky").append(nav1Html);
        }
    }

    //滚动条滚动事件
    $(window).scroll(function () {
        isShowStickyNav();
        if ($(window).scrollTop() >= 41) {
            loadFirstNav();
            loadStNav();
            //console.log(1);
        } else {
            $(".js-navsticky .navcloned.js-navcloned").hide();
            $(".js-navsticky .mod-nav-sub").hide();
        }
    });
    $(".navsticky .js-menu").hover(function () {
        $(".js-navsticky .navcloned").show();
        $(".js-navsticky .mod-nav-sub").show();
        stNavHover();
    });
    //显示置顶导航入口
    function isShowStickyNav() {
        if ($(window).scrollTop() >= 41) {
            $(".mod-nav-sticky-panel .wrapper").fadeIn(1000);
        } else {
            $(".mod-nav-sticky-panel .wrapper").stop(true, true).fadeOut(1000);
        }
    }

    //显示国际站窗口
    function showInternationalPop() {
        $(".mod-countrypicker .morph-bg").addClass("open");
        $(".mod-countrypicker .morph-bg .js-content").addClass("open");
    }

    //点击显示国际站窗口
    $(".js-navsticky .navmenu .mod-countrypicker").click(function () {
        showInternationalPop();
    });
    //关闭国际站窗口
    $(".mod-countrypicker .morph-bg .icon-close,.mod-countrypicker .morph-bg:not(.js-content)").click(function (e) {
        e.stopPropagation();
        $(".mod-countrypicker .morph-bg").removeClass("open");
        $(".mod-countrypicker .morph-bg .js-content").removeClass("open");
    });
    //搜索
    $(".js-search-link").click(function () {

        if ($(".mod-search-bar").is(":hidden")) {
            $(".mod-search-bar").show();
            $(".js-mod-nav-sub").hide();
        } else {
            $(".mod-search-bar").hide();
            $(".mod-search-result").hide();
            $("footer .mod.mod-grey-box").hide();
            $(".js-mod-nav-sub").show();
        }
        $(".js-navsticky .mod-nav-sub").hide();
    });
    $(".mod-search-bar .ga-button-primaryAction").click(function () {

        var keyword = $('#keyword_input').val();
        $.ajax({
            type: "POST",
            async: true,
            url: '/search/nobel/' + keyword,
            dataType: "json",
            success: function (data) {
                if (data.status == 'ok') {
                    var content = '<div class="container">' +
                        '<div class="result-hint js-result-hint"><strong>共搜索出 <span style="color: red">' + data.count + '条</span> 结果</strong></div>' +
                        '<div class="results js-results">';

                    for (var i = 0; i < data.results.length; i++) {
                        content += '<article><h3><a target="_blank" href="' + data.results[i].link + '">' + data.results[i].title + '</a></h3><p class="rich">' + data.results[i].snippet + '</p></article>';
                    }
                    content += '</div>';

                    if (data.count) {
                        content += '<div class="show-more js-show-more"><a href="/search/nobel/' + keyword + '" class="button js-show-more-link">显示全部</a></div>';
                    }

                    content += '</div>';

                    $(".mod-search-result").html(content);
                } else {
                }
            }
        });

        $(".mod-search-result").show();

        $("footer .mod.mod-grey-box").show();
    });
    $('#searchForm').on('submit', function (e) {
        e.preventDefault(); //阻止form表单默认提交
    });
    //鼠标移到当前图片上，其他图片变灰
    $(".par.parsys .block").hover(function () {
        $(this).siblings(".block").find("img").addClass("imggray");
        $(this).parent(".g-col").siblings(".g-col").find(".block img").addClass("imggray");
        $(this).parents(".g-row").siblings(".g-row").find(".block img").addClass("imggray");
    }, function () {
        $(this).siblings(".block").find("img").removeClass("imggray");
        $(this).parent(".g-col").siblings(".g-col").find(".block img").removeClass("imggray");
        $(this).parents(".g-row").siblings(".g-row").find(".block img").removeClass("imggray");
    });
    //手机端右侧快捷入口
    $(".js-buttons-content .js-buttons-toggle").click(function () {
        $(this).parent().toggleClass("is-active");
    });
    //详情页手风琴效果
    window.fheight = $(".g-row.g-layout-responsive-66-33").outerHeight();
    $(".js-accordion-link").click(function () {
        if ($(this).next(".js-accordion-content").is(":hidden")) {
            $(this).parent(".js-accordion-element").addClass("active");
            $(this).parents(".item").siblings(".item").find(".js-accordion-element").removeClass("active");
            $(this).parents(".item").siblings(".item").find(".js-accordion-content").hide();
            $(this).next(".js-accordion-content").slideDown();
            $("html, body").animate({scrollTop: $(this).offset().top - 30}, 800);
        } else {
            $(this).parent(".js-accordion-element").removeClass("active");
            $(this).next(".js-accordion-content").slideUp();
        }
        setTimeout(function () {
            window.fheight = $(".g-row.g-layout-responsive-66-33").outerHeight();
        }, 2000);
    });
    //colorbox
    if ($(window).innerWidth() >= 768) {
        $(".iframe").colorbox({
            inline: true,
            width: "50%",
            height: "660px",
            onOpen: function (e) {
                // $('.galleria.lightbox').galleria({
                //     width: 600,
                //     height: 450
                // });
                var pid = $(this).attr('href');

                Galleria.run(pid + ' .lightbox', {
                    width: '100%',
                    height: 500,
                });
            },
        });
    } else {
        $(".iframe").colorbox({
            inline: true,
            width: "100%",
            height: "100%",
            onOpen: function () {
                var pid = $(this).attr('href');

                Galleria.run(pid + ' .lightbox', {
                    width: '100%',
                    height: 480,
                });
            },
        });
    }

    $(".js-media-lightbox[data-media-lightbox-type='image']").colorbox();
    $(".js-media-lightbox[data-media-lightbox-type='video']").colorbox({
        iframe: true,
        innerWidth: '50%',
        innerHeight: 409
    });
    //详情页展开显示更多
    var downH = $(".automaticdownloadlist .list-wrap").height();
    $(".automaticdownloadlist .mod-list-button button").click(function () {
        var actrualH = $(this).parent().siblings(".list-wrap").find(".list-cont").height();
        if ($(this).hasClass("expand")) {
            $(this).removeClass("expand");
            $(this).find("span").text("展开全部");
            $(this).parent().siblings(".list-wrap").css("height", downH);
        } else {
            $(this).addClass("expand");
            $(this).find("span").text("收缩");
            $(this).parent().siblings(".list-wrap").css("height", actrualH);
        }
    });
    //左侧菜单折叠
    $(".navside .sub li a .js-arrow").click(function (e) {
        e.preventDefault();
        if ($(this).parent().next(".meta").is(":hidden")) {
            $(this).parents("li").addClass("open");
            $(this).parent().next(".meta").show();
        } else {
            $(this).parents("li").removeClass("open");
            $(this).parent().next(".meta").hide();
        }

    });

    //详情页登录注册框滚动

    if($(".mod-calltoaction").length>0){
        var ftop= $(".mod-calltoaction").parents(".g-row").offset().top;
        $(window).scroll(function() {
                if($(window).width()>1024){
                    var scrollTop = $(window).scrollTop();
                    var scrollBtm = ftop+fheight;
                    if ($(".mod-calltoaction").offset().top-30 <= scrollTop) {
                        //console.log(scrollTop);
                        $(".detail-lr-box").css({"position":"fixed","top":"75px","width":"290px"})
                        if (scrollBtm-scrollTop<=290) {
                            var t=290-(scrollBtm-scrollTop);
                            $(".detail-lr-box").css("top",75-t);
                        } 
                    } else{
                        $(".detail-lr-box").removeAttr("style");
                    }
                }else{
                    $(".detail-lr-box").removeAttr("style");
                }
        });
        
        $(window).resize(function() {
            if($(window).width()<=1024){
                $(".detail-lr-box").removeAttr("style");
            }
        });

    }

})(jQuery);